<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use App\Exceptions\Customize\BaseException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];
    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];
    /**
     * 定义异常返回字段
     * @author huwei
     */
    private $code;
    private $error_code;
    private $status;
    private $message;

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        /**
         * 判断传入的异常的类型，根据不同类型抛出不同的异常
         * @author huwei
         */

        if ($exception instanceof BaseException) {

            $this->code = $exception->code;
            $this->error_code = $exception->error_code;
            $this->status = $exception->status;
            $this->message = $exception->message;

        } else {

            if (config('app.debug')) {
                return parent::render($request, $exception);
            } else {
                //如果是web，渲染错误页面
                /*if(!request()->is('api/*')){
                    return response()->view('errors.default', [], 500);
                }*/

                $this->code = 500;
                $this->error_code = 10000;
                $this->status = 'FAIL';
                $this->message = '服务器内部错误';

                //此处可记录日志（生产环境）
                Log::error($exception->getMessage());

            }

        }

        /**
         * 拼接响应数组
         * @author huwei
         */
        //判断是否是api，api和非api返回不同的字段
        if (request()->is('api/*')) {
            $action = request()->n;
            $response = [
                'n' => $action,
                's' => $request->s,
                'q' => [
                    's' => $this->error_code,
                    'd' => $this->message,
                    't' => date('Y-m-d H:i:s', time())
                ]
            ];

            /**
             * 将响应输出到日志文件（保存路：/storage/app/public/logs）
             */
            if (config('app.debug')) {
                $log = '---------' . PHP_EOL . $action . PHP_EOL . date('Y-m-d H:i:s') . PHP_EOL;
                Storage::disk('public')->append('logs\api_' . date('Ymd') . '.log', $log . json_encode($response, JSON_UNESCAPED_UNICODE) . PHP_EOL);
            }

            /**
             * 返回响应
             * @author huwei
             */
            return response()->json($response, $this->code);
        } else {
            $response = [
                'error_code' => $this->error_code,
                'status'     => $this->status,
                'message'    => $this->message
            ];
            echo json_encode($response);
            die;
        }

    }
}
